package xyz.mimai.media.netty.chatroom;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * @ClassName ServerHandler
 * @Description TODO
 * @Author 方丈
 * @Date 2021/2/9 10:36
 * @Version 1.0.0
 **/
public class ServerHandler extends SimpleChannelInboundHandler<String> {

    //定义一个组管理所有的channel,GlobalEventExecutor 全局事件执行器，单例
    static final ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        channelGroup.add(ctx.channel());
        channelGroup.writeAndFlush("["+ctx.channel().remoteAddress()+"] "+"加入聊天室");
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        channelGroup.remove(ctx.channel());
        channelGroup.writeAndFlush("["+ctx.channel().remoteAddress()+"] "+"离开聊天室");
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        channelGroup.writeAndFlush("["+ctx.channel().remoteAddress()+"] "+"在线");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        channelGroup.writeAndFlush("["+ctx.channel().remoteAddress()+"] "+"离线了");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String o) throws Exception {
        channelGroup.stream().forEach(
                channel -> {
                    String echoMsg;
                    if(channelHandlerContext.channel()==channel){
                        echoMsg = "我说:"+o;
                    }else{
                        echoMsg = "["+channel.remoteAddress()+"]说:"+o;
                    }
                    channel.writeAndFlush(echoMsg);
                }
        );
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        System.out.println("["+ctx.channel().remoteAddress()+"]异常离开");
        // 当出现异常就关闭连接
        cause.printStackTrace();
        ctx.close();
    }
}
